var app = getApp();
var api = require('../../api.js');
var util = require('../../utils/util.js');
var socketOpen = false;
var frameBuffer_Data, session;
var pusherWin = true;
let socketMsgQueue = [];
var heartBeatFailCount = 0; // 心跳失败次数
var heartBeatTimeOut = null; // 终止心跳
var heart = '';
var timer;
var t;
var video_url = '';
var liveContext = '';
var timeout = 10000;
var timeoutObj = null;
var serverTimeoutObj = null;
var comment_queue = [],
  system_queue = [];
var queue_timer;
import ROP from '../../dms/dms.js';
Page({
  /**
   * 相关监听
   */
  onReady(res) {
    this.setData({
      liveContext: wx.createLivePlayerContext("livePlayer"),

    });

    this.livePusher = wx.createLivePusherContext("livePusher"),
      this.data.liveContext.src = this.data.video_url;
    var page = this;
    //连接成功
    ROP.On("enter_suc", function () {

      console.log('EnterSuc');
      // setText("EnterSuc");
    })
    //离线，以及开始重连的事件
    ROP.On("reconnect", function () {
      console.log('reconnect');
      page.initConnect()
      // setText("reconnect:");
    })
    ROP.On("offline", function (err) {
      console.log('offline' + err);
      // setText("offline:" + err);
    })
    //收到关注的话题的消息
    ROP.On("publish_data", function (data, topic) {
      page.getMsg(data);
      console.log("recv at " + topic + " -> " + data)
    })
    //连接失败
    ROP.On("enter_fail", function (err) {
      console.log("EnterFail:" + err);
    })
    //被相同ID挤掉线。
    ROP.On("connectold", function () {
      console.log("Losed");
    })
    //与服务器断开连接的事件
    ROP.On("losed", function () {
      page.closeROP()
      console.log("Losed");
    })
  },
  statechange(e) {
    console.log('live-player code:', e.detail.code)
  },
  statechanges(e) {
    console.log('live-pusher code:', e.detail.code)
  },
  error(e) {
    console.error('live-player error:', e.detail.errMsg)
  },


  /**
   * 页面的初始数据
   */
  data: {
    follow: false,
    hidden: true,
    ShowContent: true,
    HiddenShare: true,
    HiddenShare1: true,
    name: '',
    url: '',
    num: 0,
    video_id: 0,
    sku_select: {},
    roomId: '',
    roomName: '',
    roomAnthor: '',
    index: '',
    show: 0,
    isLayer: 1,
    comment_ids: [],
    live_user: {
      list: []
    },
    auth_tips: "",
    inputInfo: '一起聊天吧~',
    goodsContent: true,
    isfull: true,
    comment_data: "",
    comment_scroll: 0,
    show_back: false,
    lockReconnect: false,
    comment_list: [],
    ContentShow: true,
    beginshow: false,
    isChecked1: true,
    isChecked2: true,
    player: false,
    pusher: true,
    sourceurl: "",
    showpusher: 0,
    select: 0,
    mode: 'FHD',
    beauty: 9,
    whiteness: 9,
    autopush: false,
    device_position: 'front',
    comment_img:''

  },

  enter: function () {
    var page = this
    setTimeout(function () {
      console.log('连接：' + page.data.video_id + '_' + wx.getStorageSync('openid'))
      ROP.Enter(page.data.video.pubkey, page.data.video.subkey, page.data.video_id + '_' + wx.getStorageSync('openid'))
      page.subscribe()

    }, 100)
  },
  subscribe: function () {
    var that = this
    var page = this
    ROP.Subscribe(that.data.video.app_id + '_' + that.data.video.id)
    setTimeout(() => {
      console.log('Subscribe' + that.data.video.app_id + '_' + that.data.video.id);

      page.initConnect()
      // ROP.GETSTATUS();
    }, 300)
  },
  initConnect() {
    var page = this
    app.request({
      url: api.aodian.connect,
      method: "post",
      data: {
        id: page.data.video_id,
      },
      success: function (res) {
        if (res.errcode == 0) {

        }
      },
      complete: function (res) {}
    });
  },
  disconnect: function () {
    console.log('leave')
    setTimeout(function () {
      ROP.Leave()
    }, 100)

    this.closeROP()
  },
  closeROP() {
    var page = this
    app.request({
      url: api.aodian.close,
      method: "post",
      data: {
        id: page.data.video_id,
      },
      success: function (res) {
        if (res.errcode == 0) {}
      },
      complete: function (res) {}
    });
  },

  getMsg(data) {
    var that = this
    var onMessage = JSON.parse(data);
    var return_videoid = onMessage.video_id;
    var video_id = that.data.video_id;
    console.log('当前videoid：', video_id);
    var comment_ids = that.data.comment_ids;
    if (return_videoid == video_id) { //如果当前video_id等于推送的video_id
      if (onMessage.content || onMessage.upload_img) {
        comment_ids.push(onMessage.id);
        that.setData({
          comment_ids: comment_ids,
          ['comment_list[' + that.data.comment_list.length + ']']: onMessage,
          current_comment_index: 'comment_' + onMessage.id
        });
      } else if (onMessage.live_user) {
        // onMessage.live_user = parseInt(that.data.video.inliveuser) + parseInt(onMessage.live_user);
        that.setData({
          live_user: onMessage
        })
        if (onMessage.join_user) {
          var join_user = onMessage.join_user;
          system_queue.push(join_user);
          that.startQueue();
        }
      } else if (onMessage.type == 'reward') {
        that.setData({
          ['reward_list[' + that.data.reward_list.length + ']']: onMessage,
          current_reward_index: 'reward_' + onMessage.id
        })
        // reward_queue.push(onMessage.damu.content);
        // that.barrage.addData([onMessage.damu])
        // that.addBarrage()
      }

    }

    // console.log(that.data.comment_list);


  },

  //socket发送信息
  submitMsg: function () {
    console.log(1);
    var that = this;
    if (that.data.video.is_comment == 1) {
      wx.showToast({
        title: '您已被禁言，无法发送',
        icon: 'none'
      })
      return false;
    }
    if (that.data.comment_data.replace(/(^\s*)|(\s*$)/g, "") == "") {
      wx.showToast({
        title: '发送内容不能为空',
        icon: 'none'
      })
    } else {
      that.sendSocketMessage();
    }

  },
  //socket发送消息
  sendSocketMessage: function () {

    var that = this;

    var msg = {
      'video_id': that.data.video_id,
      'content': that.data.comment_data,
      'acct_id': app.globalData.acct_id,
      'user_id': wx.getStorageSync("user_info").user_id,
      'nickname': wx.getStorageSync("user_info").nickName,
      'avatar_url': wx.getStorageSync("user_info").avatarUrl,
      'img': that.data.comment_img ? that.data.comment_img : '',
      'type': '',
      'id': ''
    }
    app.request({
      url: api.video.add_live_comment,
      method: "post",
      data: {
        id: that.data.video_id,
        content: that.data.comment_data,
        img: that.data.comment_img,
      },
      success: function (res) {
        if (res.errcode == 0) {
          msg.id = res.data;
          that.setData({
            comment_data: '',
            comment_img: '',
            inputInfo: '一起聊天吧~'
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
        }
      },
      complete: function (res) {
        wx.hideLoading();
      }
    });
    console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))
  },
  switchCamera: function () {
    this.livePusher.switchCamera()

  },
  showContent: function () {
    this.setData({
      goodsContent: false
    })
  },

  closeContent: function () {
    this.setData({
      goodsContent: true
    })
  },


  btnShow: function () {
    this.setData({
      ContentShow: false
    })
  },
  //切换画质
  btnquality: function () {


  },
  changeSwitch1: function (event) {
    if (event.detail.value == true) {
      this.setData({
        beauty: 9
      })
    } else {
      this.setData({
        beauty: 0
      })
    }
    var Beauty = event.detail.value;
  },
  changeSwitch2: function (event) {
    if (event.detail.value == true) {
      this.setData({
        whiteness: 9
      })
    } else {
      this.setData({
        whiteness: 0
      })
    }
    var Beauty = event.detail.value;
  },


  closeShow: function () {
    this.setData({
      ContentShow: true,
      beginshow: false
    })
  },
  tobuy: function (e) {
    wx.navigateTo({
      url: '../goods-details/goods-details?goods_id=' + e.currentTarget.dataset.id,
    })
  },
  /**
   * 将焦点给到 input（在真机上不能获取input焦点）
   */
  tapInput() {
    this.setData({
      //在真机上将焦点给input
      inputFocus: true,
      //初始占位清空
      inputInfo: ''
    });
  },
  goback: function () {
    if (getCurrentPages().length > 1) {
      wx.navigateBack({
        delta: -1
      })
    } else {
      wx.redirectTo({
        url: '../index/index',
      })
    }
  },

  inputRemark(e) {
    this.setData({
      //inputInfo: e.detail.value || '一起聊天吧~',
      comment_data: e.detail.value,
      hiddenContent: true
    });
  },

  hiddenInput(e) {
    this.setData({
      hiddenContent: true
    });
  },

  /**
   * input 失去焦点后将 input 的输入内容给到cover-view
   */
  showInput(e) {
    this.setData({
      hiddenContent: false,
      inputInfo: e.detail.value || '一起聊天吧~'
    });
  },

  CloseSettlement: function () {
    this.setData({
      ShowContent: true
    })
  },

  HiddenShareContent: function () {
    this.setData({
      HiddenShare: true
    })
  },

  popup1: function () {
    this.setData({
      HiddenShare: false
    })
  },

  GeneratePosters: function () {
    this.setData({
      HiddenShare: true
    })

  },
  ClosePosters: function () {
    this.setData({
      HiddenShare1: true
    })
  },

  FHDquality: function () {
    console.log("超清")
    this.setData({
      select: 0,
      mode: 'FHD'
    })

  },
  HDquality: function () {
    console.log('高清')
    this.setData({
      select: 1,
      mode: 'HD'
    })
  },
  SDquality: function () {
    console.log("标清")
    this.setData({
      select: 2,
      mode: 'SD'
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var page = this
    if (options) {
      var tmp_options = wx.getStorageSync("tmp_options");
      if (tmp_options) {
        wx.setStorageSync("tmp_options", Object.assign(tmp_options, options))
      } else {
        wx.setStorageSync("tmp_options", options)
      }
      if (options.uid) {

        var uid = options.uid;
        if (uid) {
          page.agent(uid);
        }
      }
      if (options.showpusher) {
        this.setData({
          showpusher: options.showpusher
        })
      }
      if (options.for_video_id) {
        this.setData({
          for_video_id: options.for_video_id
        })
      }
      if (options.scene && !options.id) {
        var scene = decodeURIComponent(options.scene);
        scene = app.str2Obj(scene);
        this.setData({
          video_id: scene.id
        })
      } else if (options.id) {
        this.setData({
          video_id: options.id
        })
      }
    }

    //判断从哪里进入

    console.log('sourceurl：' + decodeURIComponent(options.sourceurl));
    this.setData({

      sourceurl: decodeURIComponent(options.sourceurl),

    })

    this.getLiveInfo(this.getLiveGoodsList);
    var user_info = wx.getStorageSync('user_info');
    this.setData({
      user_info: user_info
    })
    var page = this;
    wx.getSystemInfo({
      success(res) {
        page.setData({
          sys_info: res
        })
      }
    });


    // this.getLiveGoodsList()
    // this.getCommentList();


    wx.getSystemInfo({
      success: function (res) {
        if (res.platform == "devtools") {} else if (res.platform == "android") {
          page.setData({
            isfull: false
          })
        }
      }
    })

    // this.videoContext = wx.createVideoContext('video', this);
    // this.videoContext.requestFullScreen({ direction: 0 });
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // if (app.globalData.localSocket.readyState !== 0 && app.globalData.localSocket.readyState !== 1) {
    //   console.log('开始尝试连接WebSocket！readyState=' + app.globalData.localSocket.readyState)
    //   if (this.data.video) {
    //     this.webSocket();

    //   }
      
    //   //
    // }
    wx.setKeepScreenOn({
      keepScreenOn: true
    })

    let that = this;
    wx.onWindowResize(function (res) {
      if (res.deviceOrientation === 'landscape') {
        that.isRotating = true;
      } else {
        that.isRotating = false;
      }
    })


  },
  onHide: function () {
    var page = this;
    // app.globalData.localSocket.close({
    //   code: 1000,
    //   reason: '退出前台'
    // });
    this.setData({
      useronload: true
    });

    //clearTimeout(timer)
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var page = this;
    // app.globalData.localSocket.close({
    //   code: 1000,
    //   reason: '退出页面'
    // })
    this.setData({
      useronload: true
    });
    //page.stopHeartBeat();
    clearInterval(queue_timer);
    page.data.liveContext && page.data.liveContext.stop();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var page = this
    var user = wx.getStorageSync('user_info');
    // page.shareSuccess()
    return {
      title: page.data.video.share_title ? page.data.video.share_title : page.data.video.title,
      path: '/pages/live-class/live-class?video_id=' + this.data.video_id + '&pid=' + user.user_id,
      imageUrl: page.data.video.share_ico ? page.data.video.share_ico : this.data.video.pic_url,
      success: (res) => {
        console.log("转发成功", res);
      },
      fail: (res) => {
        console.log("转发失败", res);
      }
    }
  },




  inputMsg: function (e) {
    this.setData({
      comment_data: e.detail.value
    })
  },
  /**
   * 弹出输入框
   */
  popup: function () {
    var that = this;
    that.setData({
      show: 1,
      isLayer: 0
    })
  },
  /**
   * 取消输入框
   */
  layer: function () {
    var that = this;
    that.setData({
      show: 0,
      isLayer: 1
    })
  },

  addAddress: function () {
    wx.navigateTo({
      url: '../new-address/new-address?pay_order=1',
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: '../delivery-address/delivery-address?pay_order=1',
    })
  },
  goCart: function () {
    wx.navigateTo({
      url: '../shopping-cart/shopping-cart',
    })
    console.log(1)
  },
  //初始化获取视频信息
  getLiveInfo: function () {
    wx.showLoading({
      title: '加载中',
    })
    var page = this;
    var video_id = page.data.video_id;
    app.request({
      url: api.user.video,
      method: "post",
      data: {
        video_id: video_id
      },
      success: function (res) {
        //page.loadreward(video_id);
        if (res.errcode == 0) {
          var video = res.data.video;
          if (!res.data.live_auth) {
            page.setData({
              auth_tips: "根据平台要求，此功能已关闭"
            })
          }

          // } else 
          if (res.data.status == 0) {
            wx.showModal({
              title: '提示',
              content: '该内容已下架',
              showCancel: false,
              confirmText: '去首页',
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/index/index',
                  })
                }
              }
            })
          } else {
            if (res.data.live_auth && res.data.template == 1) {
              wx.redirectTo({
                url: '../live/detail?id=' + video_id,
              })
            } else {
              page.getCommentList()
              page.setData({
                video: res.data,
                video_id: res.data.id,
                follow: res.data.follow,
                video_url: res.data.video_url,
                showpusher: res.data.iszhubo,
                //     liveContext: wx.createLivePlayerContext("livePlayer")
              });
              if (page.data.sys_info.platform == 'ios') {
                // setTimeout(function(){
                //   page.data.liveContext.requestFullScreen({
                //     'direction': 0
                //   })
                //   var videoContext = wx.createVideoContext("video");
                //   videoContext.requestFullScreen({ direction: 0 })
                // },1500)
                page.setData({
                  show_back: false
                })

              }
              // setTimeout(function(){
              //   page.data.liveContext.src = res.data.video_url
              // },2000)
              // page.webSocket();
              page.enter()
              wx.setNavigationBarTitle({
                title: res.data.title,
              })
            }

          }
        } else if (res.errcode == 5005) {
          wx.showModal({
            title: '提示',
            content: '该内容已下架',
            showCancel: false,
            confirmText: '去首页',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index',
                })
              }
            }
          })
        } else if (res.errcode == 5001) {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false,
            confirmText: '去首页',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index',
                })
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
        }
      },
      complete: function (res) {
        wx.hideLoading();
      }
    });
  },


  //历史聊天
  getCommentList: function () {
    var page = this
    app.request({
      url: api.video.live_comment,
      method: 'POST',
      data: {
        video_id: page.data.video_id,
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            comment_list: res.data
          })
          setTimeout(function () {
            if (page.data.comment_list.length > 0) {
              page.setData({
                current_comment_index: 'comment_' + page.data.comment_list[page.data.comment_list.length - 1].id
              })
            }

            // page.queryMultipleNodes();
          }, 1000)

        } else {
          wx.showModal({
            title: '警告',
            content: res.msg,
            showCancel: false
          })
        }
      }
    });
  },
  //绑定互动消息输入
  getComment: function (e) {
    var value = e.detail.value;
    if (value.length > 0) {
      this.setData({
        showOrHidden: true,
        clickevent: true,
        comment_data: e.detail.value
      })
    } else {
      this.setData({
        showOrHidden: false,
        clickevent: false,
        state1: e.currentTarget.dataset.key + 1,
      })
    }
    // this.setData({
    //   comment_data: e.detail.value
    // });
  },
  //点击全屏
  onFullScreenClick: function () {
    var page = this
    page.data.liveContext.requestFullScreen({
      direction: 90,
      success: function (res) {
        page.setData({
          fullScreen: 1
        })
      }

    })
    console.log(this.data.fullScreen);
    if (!this.data.fullScreen) {
      this.ctx.requestFullScreen({
        direction: 0,
        success: function () {
          console.log('进入全屏模式成功!!')
        },
        complete: function () {
          wx.showToast({
            icon: 'none',
            title: '请点击屏幕退出全屏',
            duration: 2000
          })
        }
      })
      console.log(this.ctx);
      this.data.orientation = "horizontal";
    } else {
      console.log('退出全屏');
      this.ctx.exitFullScreen({

      })
      this.data.orientation = "vertical";
    }
    this.setData({
      orientation: this.data.orientation
    })
  },

  // 全屏
  onFullScreenChange: function (e) {
    console.log(e.detail.fullScreen);
    this.setData({
      fullScreen: e.detail.fullScreen
    })
    wx.showToast({
      icon: 'none',
      title: this.data.fullScreen ? '全屏' : '退出全屏',
    })
  },
  reconnect() {
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer)

    this.timer = setTimeout(() => {
      this.webSocket();
      this.lockReconnect = false;
    }, 5000);


  },

  startHeartBeat: function () {

    var that = this;
    clearTimeout(timeoutObj);
    clearTimeout(serverTimeoutObj);
    timeoutObj = setTimeout(() => {
      console.log("发送心跳");
      app.globalData.localSocket.send({
        data: JSON.stringify({
          'msg_type': 'heart'
        }),
        success() {
          console.log("心跳成功");
        }
      });
      serverTimeoutObj = setTimeout(() => {
        console.log('心跳断开连接');
        app.globalData.localSocket.close();
      }, 10000);
    }, 10000);

  },


  //socket定义
  webSocket: function () {
    // 创建Socket
    var that = this;
    // console.log(that.data.video)

    app.globalData.localSocket = wx.connectSocket({
      url: that.data.video.ws_url,
      header: {
        'content-type': 'application/json'
      },
      method: 'get',
      success: function (res) {
        console.log('WebSocket连接创建', res);
      },
      fail: function (err) {
        wx.showToast({
          title: '网络异常！',
        })
        console.log(err)
      },
    })


    app.globalData.localSocket.onOpen(res => {
      socketOpen = true;
      this.initSocket();
      //加入间
      console.log('WebSocket连接已打开！readyState=' + app.globalData.localSocket.readyState)
      console.log('监听 WebSocket 连接打开事件。', res);

    })
    app.globalData.localSocket.onClose(onClose => {
      console.log('监听 WebSocket 连接关闭事件。', onClose)
      socketOpen = false;
      if (this.data.useronload) {
        console.log('close');
      } else {
        console.log('非正常关闭,开启自动重连');
        that.reconnect();
      }

    })
    app.globalData.localSocket.onError(onError => {
      console.log('监听 WebSocket 错误。错误信息', onError)
      socketOpen = false;
      that.reconnect();
    })

    app.globalData.localSocket.onMessage(onMessage => {
      console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息', onMessage.data)
      if (onMessage.data == 'tong') {
        console.log('tong');
        that.startHeartBeat();
      } else {
        var onMessage = JSON.parse(onMessage.data);
        var return_videoid = onMessage.video_id;
        var video_id = that.data.video_id;
        console.log('当前videoid：', video_id);
        var comment_ids = that.data.comment_ids;
        if (return_videoid == video_id) { //如果当前video_id等于推送的video_id
          if (onMessage.content || onMessage.upload_img) {
            if (comment_ids.indexOf(onMessage.id) == -1) {
              // var comment_list = that.data.comment_list;
              // comment_list.push(onMessage);
              comment_queue.push(onMessage);
              that.startQueue();
              // comment_ids.push(onMessage.id);
              that.setData({
                comment_ids: comment_ids,
                // comment_list: comment_list,
                // ['comment_list[' + that.data.comment_list.length + ']']: onMessage,
                // current_comment_index: 'comment_' + onMessage.id
              });
              // if (!that.data.hiddenContent) {
              //   that.queryMultipleNodes();
              // }

            }
          } else if (onMessage.live_user) {
            onMessage.live_user = parseInt(that.data.video.inliveuser) + parseInt(onMessage.live_user);
            that.setData({
              live_user: onMessage
            })
            if (onMessage.join_user) {
              // var comment_list = that.data.comment_list;

              var join_user = onMessage.join_user;
              system_queue.push(join_user);
              that.startQueue();
              // join_user.type = 'join';
              // comment_list.push(join_user);
              // that.setData({
              //   ['comment_list[' + that.data.comment_list.length + ']']: join_user,
              //   // comment_list: comment_list,
              // });
              // if (!that.data.hiddenContent) {
              //   that.queryMultipleNodes();
              // }
            }
          }

          console.log(that.data.comment_list);
        }
      }

    })
  },
  /** 
   * 消息队列处理
   */
  startQueue: function () {
    var that = this;
    clearInterval(queue_timer);
    queue_timer = setInterval(function () {
      console.log("开始遍历");
      console.log(comment_queue);
      console.log(system_queue);
      if (comment_queue.length > 0) {
        var current_data = [];
        for (var i = 0; i < comment_queue.length > 6 ? 6 : comment_queue.length; i++) {
          current_data.push(comment_queue.shift());
        }
        var comment_list = that.data.comment_list;
        var comment_list = comment_list.concat(current_data);
        if (comment_list.length > 50) {
          comment_list = that.data.video.comment_count ? comment_list.slice(-(parseInt(that.data.video.comment_count) - 1)) : comment_list.slice(-49);
        }
        that.setData({
          comment_list: comment_list,
          current_comment_index: 'comment_' + comment_list[comment_list.length - 1].id
        })
        // that.queryMultipleNodes();
      }
      if (system_queue.length > 0) {
        var join_live_user = system_queue.shift();
        that.setData({
          join_live_user: join_live_user.nickname
        })
      } else {
        that.setData({
          join_live_user: ''
        })
      }
    }, 1200);

  },



  //初始链接socket
  initSocket: function () {
    var msg = {
      'video_id': this.data.video_id,
      'acct_id': app.globalData.acct_id,
      'openid': wx.getStorageSync("openid")
    }
    console.log('初始化连接', JSON.stringify(msg))
    this.startHeartBeat(); //开始心跳
    app.globalData.localSocket.send({
      data: JSON.stringify(msg)
    })
  },

  //socket发送信息
  // submitMsg: function () {
  //   console.log(1);
  //   var that = this;
  //   if (that.data.video.is_comment == 1) {
  //     wx.showToast({
  //       title: '您已被禁言，无法发送',
  //       icon: 'none'
  //     })
  //     return false;
  //   }
  //   if (app.globalData.localSocket.readyState != 1) {
  //     wx.showToast({
  //       title: '发送失败，连接错误',
  //       icon: 'none'
  //     })
  //     return false;
  //   }
  //   if (that.data.comment_data.replace(/(^\s*)|(\s*$)/g, "") == "") {
  //     wx.showToast({
  //       title: '发送内容不能为空',
  //       icon: 'none'
  //     })
  //   } else {
  //     that.sendSocketMessage();
  //   }

  // },
  // //socket发送消息
  // sendSocketMessage: function () {

  //   var that = this;

  //   var msg = {
  //     'video_id': that.data.video_id,
  //     'content': that.data.comment_data,
  //     'acct_id': app.globalData.acct_id,
  //     'user_id': wx.getStorageSync("openid")
  //   }

  //   console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))
  //   app.globalData.localSocket.send({
  //     data: JSON.stringify(msg),
  //     success: function (res) {
  //       wx.showToast({
  //         title: '发送成功',
  //       });
  //       that.setData({
  //         comment_data: '',
  //         inputInfo: '一起聊天吧~'
  //       });
  //     },
  //     fail: function (res) {
  //       wx.showToast({
  //         title: '发送失败',
  //         icon: none
  //       })
  //     },
  //   })


  // },




  //判断对象是否相同
  diff: function (obj1, obj2) {
    var o1 = obj1 instanceof Object;
    var o2 = obj2 instanceof Object;
    if (!o1 || !o2) {
      /*  判断不是对象  */
      return obj1 === obj2;
    }

    if (Object.keys(obj1).length !== Object.keys(obj2).length) {
      return false;
      //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
    }

    for (var attr in obj1) {
      var t1 = obj1[attr] instanceof Object;
      var t2 = obj2[attr] instanceof Object;
      if (t1 && t2) {
        return diff(obj1[attr], obj2[attr]);
      } else if (obj1[attr] !== obj2[attr]) {
        return false;
      }
    }
    return true;
  },
  //开启
  livebroadcast: function () {
    console.log('开启播了');
    this.setData({
      player: true,
      pusher: false,
      beginshow: false,
      ContentShow: true,
      autopush: true,
      showpusher: 1
    })
    app.request({
      url: api.video.myliveroom,
      method: 'POST',
      success: function (res) {

        sourceurl: res.data.sourceurl
      }
    })
  },
  previewImg(e) {
    console.log(e);
    wx.previewImage({
      urls: e.currentTarget.dataset.src,
    })
  },
  chooseImg() {
    app.upload(this.submitImg);
  },
  submitImg(e) {
    //重连
    var that = this;
    wx.showLoading({
      title: '发送中',
    })
    this.setData({
      comment_img: e.url,
    })
    setTimeout(function () {
      that.sendSocketMessage();
    }, 500);
  },
  sendImg(e) {
    // this.setData({
    //   msg_type: 'img',
    //   comment_data: e.url
    // })
    var that = this;

    var msg = {
      'video_id': that.data.video_id,
      'content': '',
      'acct_id': app.globalData.acct_id,
      'user_id': wx.getStorageSync("openid"),
      upload_img: e.url,
      type: 'img'
    }

    console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))
    app.globalData.localSocket.send({
      data: JSON.stringify(msg),
      success: function (res) {
        wx.showToast({
          title: '发送成功',
        });
        that.setData({
          comment_data: '',
          inputInfo: '一起聊天吧~'
        });
      },
      fail: function (res) {
        wx.showToast({
          title: '发送失败',
          icon: none
        })
      },
    })
    // this.sendSocketMessage()
    // console.log(e)
  },
})